import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { PageOptionsDto } from 'src/dto/page.dto';
import {
  DictItemDto,
  PageDictDto,
  PageDictItemtDto,
} from 'src/dto/dict/dict.dto';
import { DictItem } from '../../entities/dict-item.entity';
import { Dict } from '../../entities/dict.entity';

@Injectable()
export class DictService {
  constructor(
    @InjectRepository(Dict)
    private readonly dictRepository: Repository<Dict>,
    @InjectRepository(DictItem)
    private readonly dictItemRepository: Repository<DictItem>,
  ) {}
  //字典
  async createDict(dict: Dict): Promise<Dict> {
    const req = this.dictRepository.create(dict);
    return this.dictRepository.save(req);
  }
  //字典
  async updateDict(newData: Dict): Promise<any> {
    const dictToUpdate = await this.dictRepository.findOne({
      where: { id: newData.id },
    });
    if (!dictToUpdate) {
      return '修改失败，id无效';
    }
    Object.assign(dictToUpdate, newData);
    return this.dictRepository.save(dictToUpdate);
  }
  //字典
  async deleteDict(obj: Dict): Promise<any> {
    const dictToDelete = await this.dictRepository.findOne({
      where: { id: obj.id },
    });
    if (!dictToDelete) {
      throw new NotFoundException('删除失败，id无效');
    }
    return await this.dictRepository.remove(dictToDelete);
  }
  //字典配置
  async createDictItem(dictItem: DictItemDto): Promise<DictItem> {
    const dict = await this.dictRepository.findOne({
      where: { id: dictItem.dictId },
    });
    if (!dict) {
      throw new NotFoundException('指定的字典不存在');
    }

    const newItem = this.dictItemRepository.create({
      ...dictItem,
      dict: dict,
    });
    return await this.dictItemRepository.save(newItem);
  }
  //字典配置
  async updateDictItem(newData: DictItem): Promise<DictItem> {
    let item = await this.dictItemRepository.findOne({
      where: { id: newData.id },
    });
    if (!item) {
      throw new NotFoundException('删除失败，id无效');
    }
    item = this.dictItemRepository.merge(item, newData);

    return await this.dictItemRepository.save(item);
  }
  //字典配置
  async deleteDictItem(obj: DictItem): Promise<void> {
    const dictItemToDelete = await this.dictItemRepository.findOne({
      where: { id: obj.id },
    });

    if (!dictItemToDelete) {
      throw new NotFoundException('删除失败，id无效');
    }
    await this.dictItemRepository.remove(dictItemToDelete);
  }

  //字典分页条件查询
  async getDictsWithPageOptions(
    pageOptions: PageDictDto,
  ): Promise<[Dict[], number]> {
    const {
      pageSize,
      pageNo,
      description,
      dictName,
      dictCode,
      dictItems,
      ...conditions
    } = pageOptions;
    const [dicts, total] = await this.dictRepository.findAndCount({
      take: pageSize,
      skip: (pageNo - 1) * pageSize,
      where: { dictName, dictCode },
      order: { createdTime: 'DESC' },
    });

    return [dicts, total];
  }

  //字典配置分页条件查询
  async getDictItemsWithPageOptions(
    pageOptions: PageDictItemtDto,
  ): Promise<[DictItem[], number]> {
    const { pageSize, pageNo, dictId } = pageOptions; // 从 pageOptions 中解构出 dictId
    const [dictItems, total] = await this.dictItemRepository
      .createQueryBuilder('dictItem')
      .leftJoinAndSelect('dictItem.dict', 'dict') // 使用左连接关联到 Dict 实体
      .where('dict.id = :dictId', { dictId }) // 使用关联的 dict_id 字段作为查询条件
      .take(pageSize)
      .skip((pageNo - 1) * pageSize)
      .orderBy('dictItem.createdTime', 'DESC')
      .getManyAndCount();
    // 将查询结果中的 dictId 字段值转换为所需的格式
    // 将查询结果中的 dictId 字段值转换为所需的格式
    const formattedDictItems: any = dictItems.map((item) => {
      const { dict, ...rest } = item; // 解构出 dict 字段并排除在外
      return {
        ...rest, // 保留除 dict 字段外的其他字段
        dictId: dict.id as any, // 将 dict 字段替换为 dictId 字段
      };
    });
    console.log(formattedDictItems);
    return [formattedDictItems, total];
  }
  // 根据字典code查询字典项

  async getDictItemsByDictCode(dictCode: string): Promise<DictItem[]> {
    console.log(dictCode, 'dictCode');

    // 查询字典
    const dict = await this.dictRepository.findOne({
      where: { dictCode: dictCode },
    });
    console.log(dict, 'dictCode');

    if (!dict) {
      throw new NotFoundException('指定的字典不存在');
    }

    // 获取字典的id属性
    const dictId = dict.id;

    // 查询字典项
    const dictItems = await this.dictItemRepository.find({
      where: { dict: { id: dictId } },
    });

    return dictItems;
  }

  //查询所有字典配置
  async getDictConfig(): Promise<{
    [key: string]: {
      text: string;
      value: string;
      label: string;
      title: string;
    };
  }> {
    const dictConfigs = {};

    // 查询所有字典
    const dicts = await this.dictRepository.find();

    // 批量查询字典配置项
    const dictItemsMap: any = {};
    const dictIds = dicts.map((dict) => dict.id);
    const dictItems = await this.dictItemRepository.find({
      where: { dict: In(dictIds) },
      relations: ['dict'],
    });
    console.log(dictItems, 'dictItems');

    // 将字典配置项按照字典 ID 分组
    for (const item of dictItems) {
      if (!dictItemsMap[item.dict.id as any]) {
        dictItemsMap[item.dict.id as any] = [];
      }
      dictItemsMap[item.dict.id as any].push(item);
    }

    // 构建返回结果
    for (const dict of dicts) {
      const items = dictItemsMap[dict.id] || [];
      dictConfigs[dict.dictCode] = items.map((val) => {
        return {
          value: val.itemValue,
          text: val.itemText,
          label: val.itemText,
          title: val.itemText,
        };
      });
    }

    return dictConfigs;
  }
}
